<script lang="ts" setup name="XtxCity">
export type CityItem = {
code:string
level:number
name:string
areaList:CityItem[]
}

export type CityRes = {
  provinceCode: string
  provinceName: string
  cityCode: string
  cityName: string
  countyCode: string
  countyName: string
}
import { ref, watchEffect } from 'vue';
import axios from 'axios';
defineProps<{
  address:string
}>()
const emit = defineEmits<{
   (e: 'changeCity', value: CityRes): void
}>()
const active = ref(false)
const cityList = ref<CityItem[]>([])
const cacheList = ref<CityItem[]>([])
const cityRes = ref<CityRes>({} as CityRes )
async function getCityList() {
  const res = await axios.get<CityItem[]>('https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json')
  console.log(res);
cityList.value = res.data
cacheList.value = res.data
  
}

getCityList()
const selectActive = (city :CityItem )=>{
  if(city.level === 0){
    cityRes.value.provinceName = city.name
    cityRes.value.provinceCode = city.code
  }
  if(city.level === 1){
    cityRes.value.cityName = city.name
    cityRes.value.cityCode = city.code
  }
   if(city.level === 2){
    cityRes.value.countyName = city.name
    cityRes.value.cityCode = city.code
    emit('changeCity',cityRes.value)
  }
  if(!city.areaList) return active.value = false
   cityList.value = city.areaList
}
watchEffect(()=>{
  if(!active.value) cityList.value = cacheList.value
})
</script>
<template>
  <div class="xtx-city">
    <div @click="active = !active" :class="{ active }" class="select">
     <span v-if ="address" class="value">{{ address }}</span>
      <span v-else class="placeholder">请选择配送地址</span>
      
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div v-show="active" class="option">
      <span @click="selectActive(item)" class="ellipsis" v-for="item in cityList" :key="item.code">{{ item.name }}</span>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>